<?php
namespace App\Http\Controllers;

use App\Library\Service\AliCloud\CloudAuth;
use App\Library\Service\AliCloud\OSS;
use App\Library\Service\AliCloud\STS;
use App\Library\Service\Verify;
use App\Library\ThirdParty\Hospital\HospitalOpenClient;
use App\Library\ThirdParty\YiAn\YiAnService;
use App\Model\Core\Admin\AdminUserModel;
use App\Model\Core\Service\ServiceCardModel;
use App\Model\Core\Service\ServiceOrderModel;
use App\Model\Core\Service\ServiceOrderProductModel;
use App\Model\Core\Service\ServiceProviderModel;
use App\Model\Core\Service\ServiceProviderProductModel;
use App\Model\Core\User\CompanyOrderCodeModel;
use App\Model\Core\User\CompanyOrderModel;
use App\Model\Core\User\UserModel;
use App\Service\AppPush\AppPushService;
use App\Service\Core\Admin\Power\AdminUserPowerService;
use App\Service\Core\Patient\PatientOrderService;
use App\Service\Core\User\CompanyOrder\CompanyOrderService;
use App\Service\OpenApi\AdminApi\AdminOpenClient;
use App\Service\OpenApi\AppApi\AppOpenClient;
use OSS\OssClient;

class DXKController extends Controller
{
    public function index()
    {
//        dd(ServiceCardModel::getInstance()->creatCardId());
//        $res = (new STS())->assumeRole('duxiaokong');
//        dd($res);
//        dd(CompanyOrderService::getInstance()->pay('TEST0000001', '支付宝', 1000, 'dxk'));
//        dd(CompanyOrderCodeModel::getInstance()->makeCode(10));
        dd($this->apiTest());
//        $res = OSS::deleteObject('tesst.jpg');
//        dd($res);
//        $res = OSS::uploadFile('tesst.jpg', easy_attached_path('dxk2.jpg'));
//        dd($res);
        self::makeOrder(3, 1, 'P1001');
        self::makeOrder(4, 1, 'P1001');
        self::makeOrder(3, 1, 'P1002');
        self::makeOrder(4, 1, 'P1002');
        self::makeOrder(3, 2, 'P1003');
        self::makeOrder(4, 2, 'P1003');
        self::makeOrder(3, 3, 'P1004');
        self::makeOrder(4, 3, 'P1004');
        die;
        $timeStamp = '1702308264';
        $checksum = '63a99df473e3ee39ee833970f65a9e3e7eaf38ff';
        $str = '{"code":1,"msg":"验签失败","data":{"header":{"accept-encoding":["gzip,deflate"],"user-agent":["Apache-HttpClient\/4.5.14 (Java\/11.0.5)"],"request-id":["98ceb179-a761-4d69-8859-6fa41aa6b336"],"content-type":["application\/json;charset=utf-8"],"md5":["874cae7363f08a21f84e2a853c9d3669"],"checksum":["63a99df473e3ee39ee833970f65a9e3e7eaf38ff"],"curtime":["1702308264"],"accept":["text\/plain, application\/json, application\/*+json, *\/*"],"content-length":["1481"],"connection":["close"],"x-forwarded-for":["39.96.18.5"],"x-real-ip":["39.96.18.5"],"host":["health2.ezhangxiu.cn"]},"body":"{\"body\":\"jKap47nna5BB2Ky8gXT66fvEF16QbuT+9nkDoL+xFmH8fU+bL1dT0D25DOmmrJzlwJZG5eT4va0IQFB7bSG\/JFDMsOQMz9cGwuc6yoMKcqKLI+5yogt7dJVvJqawZIT0a9+GrNfz56IhM5HU2EQduZMCX9463FXniS0lToJOXt3cMqPLJxE+q2Tf6uWsr6oWtgJnER8YZGNDWZPZT90lwylrEstlRi30NJKAvLAGxbrLjBSv3eqKqcYY3nHU8UfrGmwwAEJZnbsjOucaBVrHZG0EAfUieMOHo8SRJvHm4bgN660htIpOv2rUNeIw9DImPBjDgVBEHkvyZkBrmQuFt2yoealHG5ZMFMR0wBmXL9sDd3FmE1v9CMEm5RMSriepTdMmp5ox\/Ag7ycvAC1yFXwGh49wLJO7gRKFHqRlpCL30CVKeKAkckVB9lN6O6BIg6JzKcTMN4uT3AHZ00nU2kuE6iqNeqLZMWLuW5PCbsbGgTSOcUP0ETlu4TuKvJJ3B43WmGD36iLO3M0u1DcAq2WtKWkCsW7OziDVhKrf5D5dzN9ujQFENDaWan1Zdbx3yQTsgFNl\/GvG9UJaelVnZe6c+4Z+QNE5Sc35AIS79DSry+N9bPjEkCHB35nN09aoAfxyH\/+2nI+9+5sxNqZEXirCb2ppV21oMo0+Vc2se7GdxLqJllJN1uBHp1EMXALysRZ14Qz0h66xk4kvhFSPrmVQfHg0Ry1XHJkS47\/XgCwFOu\/\/qWPcz\/EsIpxrSBaEGiM93m7OYLq1XWYt1GINDIegqwukO53KwjUogcbqfPdTD\/u+G3CnCcUtN8SugxtHmF2Xh1apOnMpeqw0a+WVpiMwXAsv58PAsoA4oY+bYi8\/ptrCKSLWMIX6ax\/PoZiAYTdJXlqDSPYVpl+99R8pWGaQbrOAecmut7SSq4yeF\/q1Tpx7VLlEKH2e88dHs0dDGs4Y\/uEUTd7WzIr5TS7aGsPJOadQ7iB5w513MFcy+mrmWqKCZaBnQybmd+BnfiHzRc7UC5eKBVSglpK3KtihbGszEkgZqrVas7qYFSsYgKreWufjCMuEUPa81tzTrwZ1GmUt7YkwjT81b5qGEywHlNQ==\",\"command\":\"familyOrderSummary\",\"fromAccount\":\"E2018053115574392102\",\"fromName\":\"和缓医生-侯三春\",\"fromPic\":\"https:\/\/imgfamily.hh-medic.com\/v2d\/photo\/20220303\/0783b87479b445c2967de69fa1d2b4e0.jpeg?x-oss-process=style\/headcss&3\",\"msgId\":\"1702308264352\",\"toAccountId\":\"10\",\"toUserToken\":\"27C8E5B14A0235C662509FB9E8C3B4A13F0D04F68EA2608F6783B874E4F50EEF\"}","all":{"body":"jKap47nna5BB2Ky8gXT66fvEF16QbuT+9nkDoL+xFmH8fU+bL1dT0D25DOmmrJzlwJZG5eT4va0IQFB7bSG\/JFDMsOQMz9cGwuc6yoMKcqKLI+5yogt7dJVvJqawZIT0a9+GrNfz56IhM5HU2EQduZMCX9463FXniS0lToJOXt3cMqPLJxE+q2Tf6uWsr6oWtgJnER8YZGNDWZPZT90lwylrEstlRi30NJKAvLAGxbrLjBSv3eqKqcYY3nHU8UfrGmwwAEJZnbsjOucaBVrHZG0EAfUieMOHo8SRJvHm4bgN660htIpOv2rUNeIw9DImPBjDgVBEHkvyZkBrmQuFt2yoealHG5ZMFMR0wBmXL9sDd3FmE1v9CMEm5RMSriepTdMmp5ox\/Ag7ycvAC1yFXwGh49wLJO7gRKFHqRlpCL30CVKeKAkckVB9lN6O6BIg6JzKcTMN4uT3AHZ00nU2kuE6iqNeqLZMWLuW5PCbsbGgTSOcUP0ETlu4TuKvJJ3B43WmGD36iLO3M0u1DcAq2WtKWkCsW7OziDVhKrf5D5dzN9ujQFENDaWan1Zdbx3yQTsgFNl\/GvG9UJaelVnZe6c+4Z+QNE5Sc35AIS79DSry+N9bPjEkCHB35nN09aoAfxyH\/+2nI+9+5sxNqZEXirCb2ppV21oMo0+Vc2se7GdxLqJllJN1uBHp1EMXALysRZ14Qz0h66xk4kvhFSPrmVQfHg0Ry1XHJkS47\/XgCwFOu\/\/qWPcz\/EsIpxrSBaEGiM93m7OYLq1XWYt1GINDIegqwukO53KwjUogcbqfPdTD\/u+G3CnCcUtN8SugxtHmF2Xh1apOnMpeqw0a+WVpiMwXAsv58PAsoA4oY+bYi8\/ptrCKSLWMIX6ax\/PoZiAYTdJXlqDSPYVpl+99R8pWGaQbrOAecmut7SSq4yeF\/q1Tpx7VLlEKH2e88dHs0dDGs4Y\/uEUTd7WzIr5TS7aGsPJOadQ7iB5w513MFcy+mrmWqKCZaBnQybmd+BnfiHzRc7UC5eKBVSglpK3KtihbGszEkgZqrVas7qYFSsYgKreWufjCMuEUPa81tzTrwZ1GmUt7YkwjT81b5qGEywHlNQ==","command":"familyOrderSummary","fromAccount":"E2018053115574392102","fromName":"和缓医生-侯三春","fromPic":"https:\/\/imgfamily.hh-medic.com\/v2d\/photo\/20220303\/0783b87479b445c2967de69fa1d2b4e0.jpeg?x-oss-process=style\/headcss&3","msgId":"1702308264352","toAccountId":"10","toUserToken":"27C8E5B14A0235C662509FB9E8C3B4A13F0D04F68EA2608F6783B874E4F50EEF"},"mySign":"0f47e93b60c513b8582423c6bc14b0f03c56c5d6"}}';
        $result = json_decode($str, true);
        $body = $result['data']['body'];
        $AppSecret = 'cDCrDJW3F0PyPNNW';
        $data = $AppSecret . md5($body) . $timeStamp;
        $mySign = sha1($data);
        $push_data['mySign'] = $mySign;
        if ($mySign != $checksum) {
            dd('验签失败');
        }
        //body
        $content = json_decode($body, true);
        $ciphertext = base64_decode($content['body']); // 需要解密的数据
        $cipherMethod = 'AES-128-CBC';
        $ivLength = openssl_cipher_iv_length($cipherMethod);
        $options = OPENSSL_RAW_DATA;
        $iv = substr(md5('AES'), 0, $ivLength);
        $result = openssl_decrypt($ciphertext, $cipherMethod, $AppSecret, $options);
        dd($ciphertext, $cipherMethod, $AppSecret, $result);
        dd($result);
        $data = [
            'user_id' => 2,
            'username' => '测试',
            'sex' => '男',
            'birthday' => '2023-10-28',
            'mobile' => '18138702771'
        ];
        $user_info = [
            'user_id' => 2,
            'username' => '测试1',
            'sex' => '女',
            'birthday' => '2023-10-28',
            'mobile' => '18138702771'
        ];
        $change_data = easy_check_change_data($user_info, $data);
        dd($change_data);
//        $res = YiAnService::getInstance()->syncUser(1);
        $res = YiAnService::getInstance()->makeOrder('2023111720054381794');
        dd($res);
        $url = 'https://wmp.hh-medic.com/wmp/launch?sdkProductId=9003&userToken=AE87BF75164F200D227EB6312C432825CCCB578FFE9820E7F43A1807648A85D9&profileName=prod';
        header('location:' . $url);
        die;
        $url = 'https://api.hh-medic.com/mock/47/familyapp/api/2.0/user/regCommon';
        $params = [
            'accountId' => 'duxiaokong',
            'sdkProductId' => 'duxiaokong',
            'name' => '杜晓孔',
            'sex' => '男',
            'birthday' => '1988-11-17',
            'phoneNum' => '18510981152',
            'cardType' => '1',
            'idCard' => '410426198811174054',
        ];
        $nonce = easy_random(32);
        $time = time();
        $app_secret = '';
        $sign = sha1($app_secret . $nonce . $time);
        $headers = [
            'Content-Type' => 'application/x-www-form-urlencoded',
            'Nonce' => $nonce,
            'CurTime' => $time,
            'CheckSum' => $sign,
        ];
        $res = easy_curl_post($url, $params, 20, $headers);
        dd($res);
        $PatientOrderService = PatientOrderService::getInstance();
        $patient_sn = '2023112010422754034';
        $res = $PatientOrderService->syncOrder($patient_sn, 0, '系统');
        dd($res);
        dd((new HospitalOpenClient())->getAccessToken());
        $res = PatientOrderService::getInstance()->caseOverSendNotice('2023111719073092207');
        dd($res);
        $AdminUserPowerService = AdminUserPowerService::getInstance();
        $res = $AdminUserPowerService->getUserMenuList(16);
        easy_p($res);
        $Client = (new AppOpenClient('FF96D96C1D77AB10AE316CCBE960682D'));
        $res = $Client->execute('patient.patientOrder.store', ['patient_id' => 1, 'illness_desc' => '咳嗽', 'duration' => '三天内']);
//        $Client->getApiDoc();
        easy_p($res);
        $res = (new AppOpenClient('FF96D96C1D77AB10AE316CCBE960682D'))->execute('user.userPatient.list');
//        $res = (new AppOpenClient())->execute('passport.login.login', ['mobile' => '18510981152', 'vcode' => 9883, 'device_id' => 'device_id']);
        easy_p($res);
        $res = CloudAuth::Id2MetaVerify('杜晓孔', '身份证号');
        dd($res);
        dd(Verify::isMobile('18510981152'));
        $res = AppPushService::getInstance()->pushNoticeToUsers([3], '通过接口发送的测试消息标题', '通过接口发送的测试消息内容', ['order_sn' => 'dxk'], ['order_sn' => 'dxk']);
        dd($res);
        $res = (new AppOpenClient())->execute('passport.login.sendCode', ['mobile' => '18510981152']);
//        $res = (new AppOpenClient())->execute('passport.login.login', ['mobile' => '18510981152', 'vcode' => 9883, 'device_id' => 'device_id']);
        easy_p($res);
        $login_res = (new AdminOpenClient())->execute('passport.login.index', ['username' => 'admin', 'password' => '123456a']);
        $res = (new AdminOpenClient($login_res['data']['access_token']))->execute('passport.login.logout');
        easy_p($res);
        dd(AdminUserModel::getInstance()->getOne(1));
    }

    public function apiTest()
    {
//        $token_res = (new AppOpenClient())->execute('passport.login.login', ['mobile' => '18510981152', 'vcode' => '888888', 'device_id' => 'device_id']);
//        dd($token_res);
        $token = 'CC83B3E1C7C237169667D4F421455F37';
        $Client = (new AppOpenClient($token));
//        $res = $Client->execute('user.user.close');
        $res = $Client->execute('service.service.activeByServiceCode', ['service_code' => '8HTCS574']);
        $Client->getApiDoc();
        dd($res);
    }

    private function makeOrder($user_id, $provider_id, $product_id)
    {
        \DB::transaction(function () use ($user_id, $product_id, $provider_id) {
            $user = UserModel::getInstance()->getOne($user_id);
            $provider = ServiceProviderModel::getInstance()->getOne($provider_id);
            $product = ServiceProviderProductModel::getInstance()->getOne($product_id);
            $order = [
                'order_sn' => ServiceOrderModel::getInstance()->createOrderSN(),
                'user_id' => $user_id,
                'username' => $user['username'],
                'mobile' => $user['mobile'],
                'company_id' => $user['company_id'],
                'order_amount' => $product['sale_price'],
                'paid_amount' => $product['sale_price'],
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => '测试',
            ];
            ServiceOrderModel::getInstance()->addOne($order);
            $order_product = [[
                'order_sn' => $order['order_sn'],
                'user_id' => $order['user_id'],
                'provider_id' => $provider['provider_id'],
                'provider_code' => $provider['provider_code'],
                'provider_name' => $provider['provider_name'],
                'product_id' => $product['product_id'],
                'product_name' => $product['product_name'],
                'product_pic' => $product['product_pic'],
                'service_user_num' => $product['service_user_num'],
                'service_month' => $product['service_month'],
                'purchase_price' => $product['purchase_price'],
                'sale_price' => $product['sale_price'],
                'valid_start_at' => $product['valid_start_at'],
                'valid_end_at' => $product['valid_end_at'],
                'active_status' => 1,
                'service_status' => 1,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => '测试',
            ]];
            ServiceOrderProductModel::getInstance()->add($order_product);
        });
    }

    public function test()
    {
        return view('test');
    }
}
